import {
  observable,
  toJS,
  // computed,
  action,
  extendObservable,
} from 'mobx'
import { topicSchema } from '../util/variable-define'
import { get } from '../util/http'

const createTopic = topic => Object.assign({}, topicSchema, topic)

class Topic {
  constructor(data) {
    extendObservable(this, data)
  }
  @observable syncing = false
}

class TopicStore {
  @observable topics
  @observable syncing
  @observable topicDetail
  @observable tab

  constructor({ syncing = false, topics = [], tab = null } = {}, topicDetail = []) {
    this.syncing = syncing
    this.topics = topics.map(topic => new Topic(createTopic(topic)))
    this.topicDetail = topicDetail.map(detail => new Topic(createTopic(detail)))
    this.tab = tab
  }

  addTopic(topic) {
    this.topics.push(createTopic(topic))
  }

  @action fetchTopics(tab) {
    return new Promise((resolve, reject) => {
      // console.log(tab, this.tab)
      // console.log(tab === this.tab)
      if (tab === this.tab) {
        resolve()
      } else {
        this.tab = tab
        // console.log(this.tab)
        this.syncing = true
        this.topics = []
        get('/topics', {
          mdrender: false,
          tab,
        }).then((resp) => {
          if (resp.success) {
            resp.data.forEach((topic) => {
              this.addTopic(topic)
            })
            resolve()
          } else {
            reject()
          }
          this.syncing = false
        }).catch((err) => {
          reject(err)
          this.syncing = false
        })
      }
    })
  }

  @action fetchSingalToptic(id) {
    return new Promise((resolve, reject) => {
      this.syncing = true
      this.topicDetail = {}
      get(`/topic/${id}`, {
        mdrender: false,
      }).then((resp) => {
        if (resp.success) {
          this.topicDetail = resp.data
          resolve()
        } else {
          reject()
        }
        this.syncing = false
      }).catch((err) => {
        this.syncing = false
        reject(err)
      })
    })
  }

  toJson() {
    return {
      topics: toJS(this.topics),
      syncing: this.syncing,
      topicDetail: toJS(this.topicDetail),
      tab: this.tab,
    }
  }
}

export default TopicStore
